package com.pospi.xstore.ui.diaob;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.BillDetailAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.CustomerBeen;
import com.pospi.xstore.dto.GoodsBeen;
import com.pospi.xstore.dto.StoreBeen;
import com.pospi.xstore.dto.SupBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.ExpandLayout;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PsCyDetailActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @Bind(R.id.time_select)
    TextView time_select;
    @Bind(R.id.billno_xz)
    TextView billno_xz;
    @Bind(R.id.cgmd_xz)
    TextView cgmd_xz;
    @Bind(R.id.gys_xz)
    TextView gys_xz;
    @Bind(R.id.cgy_xz)
    TextView cgy_xz;
    @Bind(R.id.beizhu_xz)
    TextView beizhu_xz;
    @Bind(R.id.lv_goods_cgsh)
    SwipeMenuListView lv_goods_counts;
    @Bind(R.id.et_code_counts)
    EditText et_code_counts;
    @Bind(R.id.tv_money_xz)
    TextView tv_money_xz;
    @Bind(R.id.sh_xz)
    TextView sh_xz;
    @Bind(R.id.ll_title)
    LinearLayout ll_title;
    @Bind(R.id.tv_shop_title)
    TextView tv_shop_title;
    @Bind(R.id.expandLayout)
    ExpandLayout expandLayout;
    @Bind(R.id.sh_bg)
    ImageView sh_bg;
    @Bind(R.id.save_xz)
    TextView save_xz;
    @Bind(R.id.tv_expand)
    TextView tv_expand;

    private GoodsDao dao;
    private List<GoodsBeen> goodsDtos = new ArrayList<>();

    private BillDetailAdapter adapter;
    private BillBeen cgddBeen;
    List<String> strings = new ArrayList<>();
    private List<StoreBeen> storeBeens;
    private List<CustomerBeen> customerBeens;
    private CustomerBeen customerBeen = new CustomerBeen();
    private SupBeen supBeen = new SupBeen();
    private MClearEditText sl;
    private MClearEditText dj;
    private boolean isEdite = true;
    private String billId = "0";//新单据为0
    private String billNo = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_diaobo);
        ButterKnife.bind(this);
        setTitle("配送差异单审核");
        tv_shop_title.setText("调出门店");
        ll_title.setVisibility(View.INVISIBLE);
        expandLayout.initExpand(true);
        isEdite = false;
        dao = new GoodsDao(getApplicationContext());
        time_select.setText(GetData.getYYMMDDTime());
        adapter = new BillDetailAdapter(this, goodsDtos);
        lv_goods_counts.setAdapter(adapter);
        sh_xz.setText("不同意");
        save_xz.setText("同意");
        cgddBeen = (BillBeen) getIntent().getSerializableExtra("data");
        if (cgddBeen != null) {//修改表单
            billId = cgddBeen.getId();
            billNo = cgddBeen.getBillno();
            time_select.setText(cgddBeen.getBillrq());
            billno_xz.setText(cgddBeen.getBillno());
            cgmd_xz.setText(cgddBeen.getOutmarketname());
            gys_xz.setText(cgddBeen.getInmarketname());
            getData();
            setTitle("详情");


            if (Double.parseDouble(cgddBeen.getStatus()) > 3) {//已收货
//                sh_bg.setImageResource(R.drawable.shbgs);
//                sh_xz.setVisibility(View.GONE);
                save_xz.setVisibility(View.GONE);
                sh_xz.setVisibility(View.GONE);
            }
        } else {
            cgddBeen = new BillBeen();

        }


        lv_goods_counts.setOnItemClickListener(this);


    }


    @OnClick({R.id.sh_xz, R.id.tv_expand,R.id.save_xz})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_expand:
                expandLayout.toggleExpand();
                if (expandLayout.isExpand()) {
                    tv_expand.setBackground(getResources().getDrawable(R.drawable.drop_down_selected_icon));

                } else {
                    tv_expand.setBackground(getResources().getDrawable(R.drawable.drop_down_unselected_icon));
                }
                break;
            case R.id.sh_xz://不同意
//                showConfirm();
                agree();
                break;
            case R.id.save_xz:
                disagree();
                break;
        }
    }




    //审核
    private void shBill() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("model", "bill.mbilldb");
        params.put("fun", "in_audit");
        params.put("type", "107");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("pds", getJson());
        Log.i("data", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    close();
                    Log.i("data", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    String errCode = object.getString("errCode");
                    final String errMsg = object.getString("errMsg");
                    if (errCode.equals("100")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new CircleDialog.Builder()
                                        .setTitle("提示")
                                        .setText("审核成功")
                                        .setPositive("确定", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                startActivity(DboReceiveListActivity.class);
                                                PsCyDetailActivity.this.finish();
                                            }
                                        })
                                        .show(getSupportFragmentManager());

                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new CircleDialog.Builder()
                                        .setTitle("提示")
                                        .setText("审核失败:"+errMsg)
                                        .setPositive("确定", null)
                                        .show(getSupportFragmentManager());
                            }
                        });
                    }
                    Log.i("data", object.getString("errMsg"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    //审核
    private void agree() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.mbilldb");
        params.put("fun", "billsure");
        JSONObject object = new JSONObject();
        try {
            object.put("outmarket",cgddBeen.getOutmarket() );
            object.put("inmarket", cgddBeen.getInmarket());
            object.put("billrq", cgddBeen.getBillrq());
            object.put("memo", "");
            object.put("person1", "");
            object.put("optname", "");
            object.put("optdt", "");
            object.put("billno", cgddBeen.getBillno());
            object.put("status", 1);
            object.put("id", cgddBeen.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("goods", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    close();
                    Log.i("data", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    final String msg = object.getString("errMsg");
                    String code = object.getString("errCode");
                    if (code.equals("100")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new AlertDialog.Builder(PsCyDetailActivity.this)
                                        .setTitle("提示")
                                        .setMessage("操作成功")
                                        .setPositiveButton("确定", null)
                                        .show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PsCyDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PsCyDetailActivity.this, "解析异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
    //审核
    private void disagree() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.mbilldb");
        params.put("fun", "billsurenot");
        params.put("table", "bill_dbhead");
        JSONObject object = new JSONObject();
        try {
            object.put("outmarket",cgddBeen.getOutmarket() );
            object.put("inmarket", cgddBeen.getInmarket());
            object.put("billrq", cgddBeen.getBillrq());
            object.put("memo", "");
            object.put("person1", "");
            object.put("optname", "");
            object.put("optdt", "");
            object.put("billno", cgddBeen.getBillno());
            object.put("status", 1);
            object.put("id", cgddBeen.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("goods", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    close();
                    Log.i("data", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    final String msg = object.getString("errMsg");
                    String code = object.getString("errCode");
                    if (code.equals("100")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new AlertDialog.Builder(PsCyDetailActivity.this)
                                        .setTitle("提示")
                                        .setMessage("操作成功")
                                        .setPositiveButton("确定", null)
                                        .show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PsCyDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PsCyDetailActivity.this, "解析异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    private void setJe() {
        double mo = 0;
        for (GoodsBeen dto : goodsDtos) {
            mo += dto.getSl() * dto.getDj();
        }
        tv_money_xz.setText(DoubleSave.doubleSaveTwo(mo) + "");
    }

    private void getData() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.mbilldb");
        params.put("fun", "find_detail");
        params.put("type", "998");
        JSONObject object = new JSONObject();
        try {
            object.put("id", cgddBeen.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONObject result = jsonObject.getJSONObject("result");
                    saveGoods(result);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    private void saveGoods(JSONObject response) {
        List<GoodsBeen> list = new ArrayList<>();
        try {
            JSONArray array = response.getJSONArray("detail");

            list = SaveOrderInfo.changegoodsToList(array.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }


        goodsDtos.addAll(list);
        adapter.notifyDataSetChanged();
        setJe();

    }
    private String getJson() {
        JSONObject object = new JSONObject();
        JSONObject head = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            object.put("id", billId);
            head.put("id", billId);
            head.put("id", billId);//新单据传入0
            head.put("billno", billNo);//
            head.put("status", "2");//"1"="未审核""2"="发货审核" "3"="收货审核" "4"="作废"
            head.put("jyfs", "");
            head.put("billrq", time_select.getText().toString().trim());
            head.put("memo", "");
            head.put("person1", "");
            head.put("type", "107");
            head.put("outmarket", cgddBeen.getOutmarket());
            head.put("inmarket", cgddBeen.getInmarket());
            for (GoodsBeen been : goodsDtos) {
                JSONObject detail = new JSONObject();
                detail.put("id", been.getId());
                detail.put("num", been.getNum());
                detail.put("name", been.getName());
                detail.put("goodsid", been.getId());
                detail.put("barcode", been.getBarcode());
                detail.put("spec", been.getSpec());

                detail.put("unit", been.getUnit());
                detail.put("hl", been.getHl());
                detail.put("sl", been.getSl());
                detail.put("dj", been.getDj());
                if (been.getZkl() == null) {
                    been.setZkl("1");

                }
                detail.put("zkl", been.getZkl());

                detail.put("je", been.getDj() * been.getSl() * Double.parseDouble(been.getZkl()));

                detail.put("jj", been.getJj());
                detail.put("jjje", been.getJj() * been.getSl());
                detail.put("lsj", been.getLsj());
                detail.put("lsjje", been.getLsj()*been.getSl());
                detail.put("catid", been.getCatid());
                detail.put("brandid", been.getBrandid());
                detail.put("sjsl", been.getSjsl());

                detail.put("artno", been.getArtno());
                detail.put("memo", been.getMemo());
                detail.put("baseunit", been.getBaseunit());
                detail.put("jhl", been.getJhl());
                detail.put("junit", been.getJunit());
                array.put(detail);
            }
            object.put("head", head);
            object.put("detail", array);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object.toString();
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//        if (!isEdite) {
//            Toast.makeText(this, "已审核，不可编辑", Toast.LENGTH_SHORT).show();
//            return;
//        }
        final GoodsBeen goodsBeen = goodsDtos.get(i);
        new CircleDialog.Builder(this)
                .setBodyView(R.layout.dialog_layout, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        sl = view.findViewById(R.id.et_goods_num);
                        dj = view.findViewById(R.id.et_goods_dj);
                        String s = goodsBeen.getSl() + "";
                        String d = goodsBeen.getDj() + "";
                        sl.setText(s);
                        dj.setText(d);
                        sl.setSelection(s.length());
                        dj.setSelection(d.length());
                        sl.setOnClearClickListener(new MClearEditText.OnClearClickListener() {
                            @Override
                            public void onClick() {
                                isHide = true;
                            }
                        });
                        dj.setOnClearClickListener(new MClearEditText.OnClearClickListener() {
                            @Override
                            public void onClick() {
                                isHide = true;
                            }
                        });
                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        if (isNumber(sl.getText().toString().trim())) {
                            goodsBeen.setSl(Double.parseDouble(sl.getText().toString().trim()));
                        }
                        if (isNumber(dj.getText().toString().trim())) {
                            goodsBeen.setDj(Double.parseDouble(dj.getText().toString().trim()));
                        }
                        adapter.notifyDataSetChanged();
                        setJe();

                    }
                })
                .setCancelable(false)
                .setTitle(goodsBeen.getName())
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                    }
                })
                .show();

    }

    public static boolean isNumber(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    private void showConfirm() {
        new CircleDialog.Builder()
                .setTitle("提示")
                .setText("是否审核?")
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shBill();
                    }
                })
                .setNegative("取消", null)
                .show(getSupportFragmentManager());
    }

    private boolean isHide = false;

    private void hintKbOne() {
        if (isHide) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 得到InputMethodManager的实例
            if (imm.isActive()) {
                // 如果开启
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_NOT_ALWAYS);

            }
            isHide = false;
        }

    }


}
